//
//  SLAFNetWorkingTool.m
//  SimpleLife
//
//  Created by 张树林 on 15/10/31.
//  Copyright (c) 2015年 张树林. All rights reserved.
//

#import "SLAFNetWorkTool.h"
#import <CommonCrypto/CommonDigest.h>

@implementation SLAFNetWorkTool

+ (void)getWithURL:(NSString *)URLStr
            cookie:(NSString *)cookie
           success:(SUCCESS_BLOCK)successBlock
           failure:(FAILURE_BLOCK)failureBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
#warning 把url整体转码会出现问题
//    NSString *URL = [URLStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", @"application/x-javascript", @"application/x-www-form-urlencoded", nil]];
    
    if (cookie) {
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    
    [manager GET:URLStr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        successBlock(responseObject);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        failureBlock(error);
    }];
                     
}


+ (void)postWithURL:(NSString *)URLStr
         parameters:(id)parameters cookie:(NSString *)cookie
            success:(SUCCESS_BLOCK)successBlock
            failure:(FAILURE_BLOCK)failureBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
//    NSString *URL = [URLStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain", @"application/x-javascript", @"application/x-www-form-urlencoded", nil]];
    
    if (cookie) {
        [manager.requestSerializer setValue:cookie forHTTPHeaderField:@"Cookie"];
    }
    
    [manager POST:URLStr parameters:parameters success:^(NSURLSessionDataTask *task, id responseObject) {
       
        successBlock(responseObject);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
       
        failureBlock(error);
        
    }];
}


+ (void)postWithURL:(NSString *)URLStr
            bodyStr:(NSString *)bodyStr
             cookie:(NSString *)cookie
            success:(SUCCESS_BLOCK)successBlock
            failure:(FAILURE_BLOCK)failureBlock
{
    NSDictionary *bodyDic = [self convertStrToBodyDic:bodyStr];
    
    [self postWithURL:URLStr parameters:bodyDic cookie:cookie success:successBlock failure:failureBlock];
}


+ (NSDictionary *)convertStrToBodyDic:(NSString *)bodyStr
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    NSArray *paraArray = [bodyStr componentsSeparatedByString:@"&"];
    for (NSString *tempStr in paraArray) {
        NSArray *keyValueArray = [tempStr componentsSeparatedByString:@"="];
        [dic setObject:keyValueArray[1] forKey:keyValueArray[0]];
    }
    
    NSDictionary *bodyDic = [dic copy];
    
    return bodyDic;
}


+ (void)cacheGetWithURL:(NSString *)URLStr
                 cookie:(NSString *)cookie
                success:(SUCCESS_BLOCK)successBlock
                failure:(FAILURE_BLOCK)failureBlock
{
    // cache文件路径
    NSString *cacheDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    NSString *fileName;
    if (cookie) {
        fileName = [self sha1:[NSString stringWithFormat:@"%@_%@", URLStr, cookie]];
    } else {
        fileName = [self sha1:URLStr];
    }
    
    NSString *cacheFilePath = [cacheDirPath stringByAppendingPathComponent:fileName];
    NSLog(@"cacheFielPath ====== %@", cacheFilePath);
    
    [self getWithURL:URLStr cookie:cookie success:^(id responseObject) {
        
        successBlock(responseObject);
        
        NSData *responseData = [NSKeyedArchiver archivedDataWithRootObject:responseObject];
        [responseData writeToFile:cacheFilePath atomically:YES];
        
    } failure:^(NSError *error) {
        
        NSData *responseData = [NSData dataWithContentsOfFile:cacheFilePath];
        
        if (responseData) {
            id responseObject = [NSKeyedUnarchiver unarchiveObjectWithData:responseData];
            successBlock(responseObject);
        } else {
            failureBlock(error);
        }
    }];
}


+ (void)cachePostWithURL:(NSString *)URLStr
                 bodyStr:(NSString *)bodyStr
                  cookie:(NSString *)cookie
                 success:(SUCCESS_BLOCK)successBlock
                 failure:(FAILURE_BLOCK)failureBlock
{
    NSString *cacheDirPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    
    NSString *fileName;
    if (cookie) {
        fileName = [self sha1:[NSString stringWithFormat:@"%@_%@_%@", URLStr, bodyStr, cookie]];
    } else {
        fileName = [self sha1:[NSString stringWithFormat:@"%@_%@", URLStr, bodyStr]];
    }
    
    NSString *cacheFilePath = [cacheDirPath stringByAppendingPathComponent:fileName];
    
    
    [self postWithURL:URLStr bodyStr:bodyStr cookie:cookie success:^(id responseObject) {
        
        successBlock(responseObject);
        
        NSData *responseData = [NSKeyedArchiver archivedDataWithRootObject:responseObject];
        [responseData writeToFile:cacheFilePath atomically:YES];
        
    } failure:^(NSError *error) {
        
        NSData *responseData = [NSData dataWithContentsOfFile:cacheFilePath];
        
        if (responseData) {
            id responseObject = [NSKeyedUnarchiver unarchiveObjectWithData:responseData];
            successBlock(responseObject);
        } else {
            failureBlock(error);
        }
    }];
}


+ (NSString*) sha1:(NSString*)input
{
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (unsigned int)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    return output;
}


+ (void)startMonitorNet
{
    AFNetworkReachabilityManager *netManager = [AFNetworkReachabilityManager sharedManager];
    
    [netManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSDictionary *infoDic = @{@"netStatus": @(status)};
        
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"NotificationNetStatus" object:nil userInfo:infoDic];
        
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWiFi:
                // WiFi
                NSLog(@"Wifi");
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                // 2G/3G/4G
                NSLog(@"2G/3G/4G");
                break;
            case AFNetworkReachabilityStatusNotReachable:
                // 没有网络
                NSLog(@"没有网络");
                break;
            case AFNetworkReachabilityStatusUnknown:
                // 未知网络
                NSLog(@"未知网络");
                break;
                
            default:
                break;
        }
    }];
    
    [netManager startMonitoring];
}


+ (void)stopMonitorNet
{
    AFNetworkReachabilityManager *manger = [AFNetworkReachabilityManager sharedManager];
    
    [manger stopMonitoring];
}


+ (BOOL)reachable
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
        
    return manager.isReachable;
}


+ (AFNetworkReachabilityStatus)netStatus
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    return manager.networkReachabilityStatus;
}




@end
